package com.nit.tools.doc;

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.XMLWorkerHelper;

import java.io.*;
import java.nio.charset.Charset;

public class Html2Pdf {
    public static void main(String[] args) {
        new Html2Pdf().createPdf();
    }

    public void createPdf() {
        try {
            String pdfDest = "D:\\doc\\doc_test\\aaa.pdf";
//            String indexhtml = "D:\\doc\\doc_test\\index_v7.html";

            String indexhtml= "D:/doc/doc_test/ftl/index_v10.html";
//	String pdfDest ="/opt/aaa.pdf";
//	String indexhtml ="/opt/index_v6.html";

//	BaseFont bfChinese = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", false);
            BaseFont bfChinese = BaseFont.createFont("C:\\WINDOWS\\Fonts\\simsun.ttc,0", BaseFont.IDENTITY_H, true);
//	BaseFont bfChinese = BaseFont.createFont("/usr/share/fonts/Fonts/simsunb.ttf", BaseFont.IDENTITY_H, true);
//	BaseFont bfChinese = BaseFont.createFont("/opt/SimSun.ttf", BaseFont.IDENTITY_H, true);

            Font font = new Font(bfChinese, 20, Font.BOLD);

//	Document document = new Document(PageSize.A4, 10, 10, 10, 10);
            Document document = new Document(PageSize.A4);

            PdfWriter mPdfWriter = PdfWriter.getInstance(document, new FileOutputStream(pdfDest));
            document.open();
            Paragraph title = new Paragraph("特殊困难老人家庭适老化改造验收表", font);
            title.setAlignment(Element.ALIGN_CENTER);
            title.setFont(font);

            document.add(title);

//	String s = getHtml();
            String s = aaaaa(indexhtml);
            System.out.print(s);
            ByteArrayInputStream bin = new ByteArrayInputStream(s.getBytes());
            XMLWorkerHelper.getInstance().parseXHtml(mPdfWriter, document, bin, Charset.forName("UTF-8"), new Itext5HtmlToPDF.ChinaFontProvide());
            document.close();
            mPdfWriter.close();
            System.out.println("okkkkkkkk");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static String aaaaa(String args) {
        try {
            // 创建一个File对象，指定要读取的文件路径
            File file = new File(args);

            // 创建一个BufferedReader对象，将其与FileInputStream关联起来
            BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));

            String reslt = "";
            String line;
            while ((line = reader.readLine()) != null) {
                reslt += line;
            }

            // 关闭reader
            reader.close();

            return reslt;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

}
